<template>
  <div>
    <!-- 查询表单 -->
    <el-card class="!border-none mb-4" shadow="never">
      <el-form class="mb-[-16px]" :model="queryParams" inline>
        <el-form-item label="正向提示词" prop="positive_prompt">
          <el-input 
            class="w-[280px]" 
            v-model="queryParams.positive_prompt" 
            clearable 
            placeholder="请输入正向提示词" 
            @keyup.enter="resetPage"
          />
        </el-form-item>
        
        <el-form-item label="创建时间" prop="create_time">
          <daterange-picker
            v-model:startTime="queryParams.start_time"
            v-model:endTime="queryParams.end_time"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 列表卡片 -->
    <el-card class="!border-none" v-loading="pager.loading" shadow="never">
      <el-button type="primary" @click="handleAdd">
        <template #icon>
          <icon name="el-icon-Plus" />
        </template>
        新增
      </el-button>
      
      <div class="mt-4">
        <el-table :data="pager.lists" stripe>
          <el-table-column label="ID" prop="id" width="80" />
          <el-table-column label="正向提示词" prop="prompt"  />
          <el-table-column label="反向提示词" prop="negative_prompt"  />
          <el-table-column label="图片分辨率" prop="size" width="120" />
          <el-table-column label="任务ID" prop="task_id" width="120" />
          <el-table-column label="任务状态" prop="task_status" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.task_status) as any">
                {{ getStatusText(row.task_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="图片地址" prop="img_url" width="120">
            <template #default="{ row }">
              <el-button 
                v-if="row.img_url" 
                type="primary" 
                link 
                @click="previewImage(row.img_url)"
              >
                预览
              </el-button>
              <span v-else class="text-gray-400">暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="create_time" width="180">
            <template #default="{ row }">
              {{ row.created_at }}
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="update_time" width="180">
            <template #default="{ row }">
              {{ row.updated_at }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="flex mt-4 justify-end">
        <pagination v-model="pager" @change="getLists" />
      </div>
    </el-card>
    
    <!-- 新增弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增AI海报设计"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        ref="formRef"
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="正向提示词" prop="positive_prompt">
          <el-input
            v-model="formData.positive_prompt"
            type="textarea"
            :rows="8"
            placeholder="正向提示词，用来描述生成图像中期望包含的元素和视觉特点。

支持中英文，长度不超过800个字符，每个汉字/字母占一个字符，超过部分会自动截断。

示例值：一只坐着的橘黄色的猫，表情愉悦，活泼可爱，逼真准确。"
          />
          <div class="mt-2 text-sm text-gray-500">
            提示词的使用技巧请参见
            <el-link 
              type="primary" 
              :href="'https://help.aliyun.com/zh/model-studio/text-to-image-prompt?spm=a2c4g.11186623.0.0.558b4680WJgDAi#d39c23e786ezd'" 
              target="_blank"
            >
              文生图Prompt指南
            </el-link>
            。
          </div>
        </el-form-item>
        
        <el-form-item label="反向提示词" prop="negative_prompt">
          <el-input
            v-model="formData.negative_prompt"
            type="textarea"
            :rows="8"
            placeholder="反向提示词，用来描述不希望在画面中看到的内容，可以对画面进行限制。

支持中英文，长度不超过500个字符，超过部分会自动截断。

示例值：低分辨率、错误、最差质量、低质量、残缺、多余的手指、比例不良等。"
          />
        </el-form-item>
        
        <el-form-item label="图片分辨率" prop="image_resolution">
          <el-select v-model="formData.image_resolution" placeholder="请选择图片分辨率">
            <el-option label="512x512" value="512*512" />
            <el-option label="1440x1440" value="1440*1440" />
            <el-option label="512x1440" value="512*1440" />
            <el-option label="1440x512" value="1440*512" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewImageUrl"
      :url-list="[previewImageUrl]"
      @close="previewImageUrl = ''"
    />
  </div>
</template>

<script setup lang="ts" name="aiPoster">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getAiPosterList, addAiPoster, type AiPosterItem } from '@/api/ai-poster'
import { usePaging } from '@/hooks/usePaging'
import { timeFormat } from '@/utils/util'
import feedback from '@/utils/feedback'

// 查询参数
const queryParams = reactive({
  positive_prompt: '',
  start_time: '',
  end_time: ''
})

// 分页数据
const { pager, getLists, resetPage, resetParams } = usePaging({
  fetchFun: getAiPosterList,
  params: queryParams
})

// 弹窗相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const formData = reactive({
  positive_prompt: '',
  negative_prompt: '',
  image_resolution: ''
})

// 表单验证规则
const formRules: FormRules = {
  positive_prompt: [
    { required: true, message: '请输入正向提示词', trigger: 'blur' }
  ],
  image_resolution: [
    { required: true, message: '请选择图片分辨率', trigger: 'change' }
  ]
}

// 图片预览
const previewImageUrl = ref('')

// 获取任务状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '任务排队中',
    'RUNNING': '任务处理中',
    'SUCCEEDED': '任务执行成功',
    'FAILED': '任务执行失败',
    'CANCELED':'任务取消成功',
    'UNKNOWN':'任务不存在或状态未知'
  }
  return statusMap[status] || 'info'
}

// 获取任务状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '任务排队中',
    'RUNNING': '任务处理中',
    'SUCCEEDED': '任务执行成功',
    'FAILED': '任务执行失败',
    'CANCELED':'任务取消成功',
    'UNKNOWN':'任务不存在或状态未知'
  }  
  return statusMap[status] || status
}

// 新增处理
const handleAdd = () => {
  dialogVisible.value = true
  // 重置表单数据
  Object.assign(formData, {
    positive_prompt: '',
    negative_prompt: '',
    image_resolution: ''
  })
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    await addAiPoster(formData)
    
    ElMessage.success('已加入到队列，请稍后查看执行结果')
    dialogVisible.value = false
    getLists()
  } catch (error) {
    console.error('新增失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 预览图片
const previewImage = (url: string) => {
  previewImageUrl.value = url
}

// 初始化数据
getLists()
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 